/*submit add catalogs function*/
var submit_catalogs = function () {
	var orderId   = $.trim($('input[name=orderId]').val()),
		name 	  = $.trim($('input[name=name]').val()),
		$catalogs = $('#catalogs');

	/*Change form on loading status*/
	$catalogs.addClass('loading');

	$.myAjax(
		_CTX_PATH_ + '/note/catalogs/add',
		{
			orderId : orderId,
			name    : name
		}, function (data) {
			/*Remove loading status*/
			$catalogs.removeClass('loading');
			if (data.result == true) {
				alert('添加分类成功');
				window.location.reload();
			} else {
				$catalogs.form('add errors', data.error).addClass('error');
			}
		}
	);
}

/*submit modify catalog function*/
var submit_modifyCatalog = function () {
	var orderId   = $.trim($('input[name=orderId]').val()),
		name 	  = $.trim($('input[name=name]').val()),
		id        = $.trim($('input[name=id]').val()),
		$modifyCatalog = $('#modifyCatalog');

	/*Change form on loading status*/
	$modifyCatalog.addClass('loading');

	$.myAjax(
		_CTX_PATH_ + '/note/catalogs/modify/' + id,
		{
			orderId : orderId,
			name    : name
		}, function (data) {
			/*Remove loading status*/
			$modifyCatalog.removeClass('loading');
			if (data.result == true) {
				alert('修改分类成功');
				window.location.href = _CTX_PATH_ + '/note/catalogs';
			} else {
				window.location.href = data.url;
			}
		}
	);
}

var catalogs = function () {
	$('#catalogs').form({
		orderId : {
			identifier : 'orderId',
			rules : [
				{
					type : 'isNumeric',
					prompt : '排序值不是数字'
				}
			]
		},
		name : {
			identifier : 'name',
			rules : [
				{
					type : 'empty',
					prompt : '分类名称不能为空'
				}
			]
		}
	}, {
		onSuccess : submit_catalogs
	});
	
	$('#modifyCatalog').form({
		orderId : {
			identifier : 'orderId',
			rules : [
				{
					type : 'isNumeric',
					prompt : '排序值不是数字'
				}
			]
		},
		name : {
			identifier : 'name',
			rules : [
				{
					type : 'empty',
					prompt : '分类名称不能为空'
				}
			]
		}
	}, {
		onSuccess : submit_modifyCatalog
	});
	
	$('a.deleteCatalog').on('click', function(event) {
		event.preventDefault();
		
		var $a = $(this),
			href = $a.attr('href');
			
		$.myAjax(
			href,
			'',
			function (data) {
				if (data.result == true) {
					alert('删除分类成功！');
					$a.parent().parent().remove();
				} else {
					alert('删除分类失败！');
				}
			},
			'get'
		);
	});
	
};

$(document).ready(catalogs);